<template>
  <div>
    <table class="table table-bordered">
      <thead>
        <tr>
          <td>序号</td>
          <td>商品名称</td>
          <td>价格</td>
          <td>数量</td>
          <td>总价</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in car_item" :key="index">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>
            <button @click="add(index)">+</button>
            <input type="text" v-model="item.num" />
            <button @click="dis(index)">-</button>
          </td>
          <td>{{item.price_sum}}</td>
        </tr>
      </tbody>
    </table>
    <div>
      总计：
      <span>{{sum}}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "Car",
  props: ["car_item"], //[{},{}]  obj.num
  data() {
    return {
      sum: 0
    };
  },

  components: {},

  computed: {},

  beforeMount() {},

  mounted() {},

  methods: {
    add(index) {
      let item = this.car_item[index];
      item.num += 1;
      item.price_sum = item.num * item.price;
    },
    dis(index) {
      let item = this.car_item[index];
      item.num -= 1;
      if (item.num < 0) {
        item.num = 0;
      }
      item.price_sum = item.num * item.price;
    }
  },

  watch: {
    car_item: {
      handler(value) {
        console.log(value);
        // 累加器数组求和
        this.sum = value.reduce((total, item) => {
          return total + item.price_sum;
        }, 0);
      },
      deep: true
    }
  }
};
</script>
<style lang='' scoped>
</style>